
<script setup>
import { reactive, ref, onMounted } from 'vue';
import MapSelector from '../common/MapSelector.vue';
// 确保引入Element Plus的消息提示（如果用到）
import { ElMessage } from 'element-plus';
import { queryPageList } from '@/apis/productAPI';
import { userStatusMap} from '@/utils/dict';
import { insertSupplier } from '@/apis/productAPI';
import { updateSupplier,deleteSupplier } from '@/apis/productAPI';
// import { queryProductTypeList } from '@/apis/productAPI';
// 1. 表格数据源必须是数组（每个元素对应一行）
import { watch } from 'vue';
const supplierInfoList = reactive([
]);

const handleSearch = () => {
   params.pageNo=1;
   fetchData();
}
// 2. 编辑对话框相关状态
const isEditDialogOpen = ref(false); // 控制对话框显示/隐藏
const currentSupplierInfo = reactive({
  id:'',
  supplierName:'',
  address:'',
  status:'',
  phone:''
});
const supplierInfoForm = reactive({
   supplierName:'',
   address:'',
   phone:'',
   status:1
});
const addressInfo = ref({
  address: '',
  longitude: '',
  latitude: ''
});

watch(
  () => addressInfo.value.address,
  (newAddress) => {
    params.address = newAddress; // 同步到 params
  }
);
// 3. 页面加载时填充数据（模拟接口请求）
onMounted(async () => {
  await fetchData();
});
const isAddOpen=ref(false);
// 分页相关变量

const currentPage = ref(1);      // 当前页码
const pageSize = ref(5);         // 每页条数，默认5条



// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;  // 重置为第一页
  fetchData(); // 重新请求
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData(); // 关键：切换页码后重新请求数据
};

// 4. 编辑功能
const openDialog = (productInfo) => {
  // 复制当前设备数据到编辑表单
  Object.assign(currentSupplierInfo, productInfo);
  isEditDialogOpen.value = true;
};

// 5. 保存编辑
const saveSupplierInfo = async() => {
  try{
    console.log("完整的编辑数据",currentSupplierInfo);
    const response =await updateSupplier(currentSupplierInfo);
    console.log("后端响应：", response); // 查看后端是否返回成功标识
    ElMessage.success("编辑成功");
    fetchData();
  }catch{
    ElMessage.error("编辑失败")
  }finally{
    isEditDialogOpen.value=false;
  }
};

// 6. 删除功能
const deleteSupplierInfo = async(supplierInfo) => {
  // 从 scope.row 中获取要删除的id（先校验id是否存在）
  const deleteId = supplierInfo.id;
  try {
    await deleteSupplier(deleteId);
    // 后端删除成功后，删除本地列表中的对应数据
    const index = supplierInfoList.findIndex(item => item.id === deleteId);
    fetchData();
    if (index !== -1) {
     supplierInfoList.splice(index, 1);
    }
    ElMessage.success('删除成功');
    fetchData();
  } catch {
    ElMessage.error("删除失败");
  }
};
const addSupplierInfo=async(supplierInfoForm)=>{
  try{
    await insertSupplier(supplierInfoForm);
    console.log("完整的插入数据", supplierInfoForm);
    ElMessage.success("添加成功");
    fetchData();
  }catch(error){
    console.error("添加失败",error)
    ElMessage.error("添加失败");
  }finally{
    isAddOpen.value=false;
  }
}
const params=reactive({
  pageNo:'',
  pageSize:'',
  status:'',
  supplierName:'',
  address:''
});

const total=ref(0);
const fetchData = async() => {
  try{
      params.pageNo=currentPage.value;
      params.pageSize=pageSize.value;
      const {data}=await queryPageList(params);
      const {records}=data;
      supplierInfoList.splice(0, supplierInfoList.length, ...records);
      total.value=data.total;
  }catch{
    ElMessage.error("加载失败")
  }
}
</script>
<template>
  <div class="container">
    <div class="supplierInfo-header">
     <div class="search-box">
       <el-input v-model="params.supplierName" placeholder=" 请输入姓名搜索" style="width: 150px;"/>
        <el-select v-model="params.status" placeholder="状态" style="margin-left: 10px; width: 150px;" clearable >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;"> 搜索</el-button>
     </div>
     <el-button class="addBtn" type="primary" @click="isAddOpen=true">添加</el-button>
    </div>
    <!-- 表格必须绑定数组数据 -->
    <div class="table_container">
      <el-table :data="supplierInfoList" border   style="width: 900px;min-height: 100%;">
        <el-table-column label="ID" prop="id" min-width="80%" width="80%"/>
        <el-table-column label="名称" prop="supplierName" min-width="80%"/>
        <el-table-column label="电话" prop="phone" min-width="80%" />
        <el-table-column label="地址" prop="address"  min-width="90%"/>
        <el-table-column label="状态" prop="status" min-width="80%">
            <template #default="scope">
              <el-tag type="priamry" v-if="scope.row.status === 1">{{ userStatusMap[scope.row.status] ?? '未知' }}</el-tag>
              <el-tag type="error" v-if="scope.row.status === 0">{{ userStatusMap[scope.row.status] ?? '未知' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100%" >
          <template #default="scope">  <!-- 必须用template包裹按钮 -->
            <el-button @click="openDialog(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteSupplierInfo(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container" style="margin-top: 15px; text-align: right;">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          page-sizes=5
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
    </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="isEditDialogOpen" title="编辑供应商" >
      <el-form :model="currentSupplierInfo">
        <el-form-item label="ID" label-width="50px" readonly>
          <el-input v-model="currentSupplierInfo.id"></el-input>
        </el-form-item>
        <el-form-item label="名称" label-width="50px">
          <el-input v-model="currentSupplierInfo.supplierName"    type="text"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="50px">
          <el-input v-model="currentSupplierInfo.phone"    type="text"></el-input>
        </el-form-item>
       <el-form-item label="地址" label-width="50px">
          <MapSelector v-model="currentSupplierInfo.address">
            <template #address-input>
              <el-input v-model="currentSupplierInfo.address" />
            </template>
          </MapSelector>
          </el-form-item>
        <el-form-item label="状态" label-width="50px">
          <el-select v-model="currentSupplierInfo.status">
            <el-option label="禁用" :value="0"/>
            <el-option label="启用" :value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isEditDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveSupplierInfo">保存</el-button>
      </template>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog v-model="isAddOpen" title="添加供应商" @close="resetForm">
      <el-form :model="supplierInfoForm">
        <el-form-item label="名称" label-width="50px">
          <el-input v-model="supplierInfoForm.supplierName" type="text"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="50px">
          <el-input v-model="supplierInfoForm.phone" type="text"></el-input>
        </el-form-item>
         <el-form-item label="地址" label-width="50px">
          <MapSelector v-model="addressInfo.address" >
        <!-- 通过插槽传入地址输入框 -->
            <template #address-input>
              <el-input v-model="addressInfo.address" placeholder="请输入地址或通过地图选择"/>
            </template>
          </MapSelector>
        </el-form-item>
        <el-form-item label="状态" label-width="50px">
          <el-select v-model="supplierInfoForm.status">
            <el-option label="启用" :value="1" selected/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isAddOpen = false">取消</el-button>
        <el-button type="primary" @click="addSupplierInfo(supplierInfoForm)">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.container {
  padding: 20px;
  background-color: white;
  min-height: 100vh; /* 使用100vh确保占满视口高度，100%可能因父元素高度问题无效 */
  width: 100%;
  // display: flex; /* 开启Flex布局 */
  // flex-direction: column; /* 子元素垂直排列 */
  // align-items: center; /* 水平居中 */
  // justify-content: flex-start; /* 垂直从顶部开始排列，可根据需要调整 */
}
.pagination-container {
  padding: 10px 0;
  align-items: center;
}
.supplierInfo-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中对齐 */
  padding-left: 15px;
  padding-right: 15px; /* 右侧留与左侧相同的间距 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
  margin-bottom: 15px; /* 与下方表格保持距离 */
}
.search-box {
  padding-left: 15px;
  display: flex; /* 使用Flex布局使输入框和按钮横向排列 */
  align-items: center; /* 垂直居中对齐 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
}


/* 表格容器 */
.table_container {
  background-color: white;
  height: 300px;
  width: calc(100% - 30px); /* 宽度与搜索框一致 */
  margin-left: 15px; /* 左侧外边距15px，与搜索框padding-left匹配 */
  margin-top: 40px;
  box-sizing: border-box; /* 避免边框/内边距影响宽度 */
}
</style>
